package cn.tpshion.task.server;

import cn.tpshion.task.common.MsgAction;
import cn.tpshion.task.data.MsgData;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class HeartbeatHandler extends ChannelInboundHandlerAdapter {

    // 心跳间隔（小于服务端超时时间）
    private static final int HEARTBEAT_INTERVAL = 25; // 秒

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        // 连接建立后启动心跳定时任务
        scheduleHeartbeat(ctx);
        ctx.fireChannelActive();
    }

    private void scheduleHeartbeat(ChannelHandlerContext ctx) {
        ctx.executor().scheduleAtFixedRate(() -> {
            if (ctx.channel().isActive()) {
                ctx.writeAndFlush(MsgData.ofJson(MsgAction.HEARTBEAT, "HEARTBEAT"));
                log.debug("send task server heartbeat");
            }
        }, HEARTBEAT_INTERVAL, HEARTBEAT_INTERVAL, TimeUnit.SECONDS);
    }
}
